package com.fly.estore.framework.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fly on 2016/3/25.
 */
public class CookieUtil {

    private final static int DEFAULT_COOKIE_MAX_AGE = 365 * 24 * 60 * 60;

    public final static String ACCOUNT_COOKIE = "account_session_id";

    public static void writeCookie(HttpServletResponse response, String name, String value){
        writeCookie(response, name, value, "/", DEFAULT_COOKIE_MAX_AGE);
    }

    public static void writeCookie(HttpServletResponse response, String name, String value, String path, int maxAge){
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static String readCookie(HttpServletRequest request, String name){
        String value = "";
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    break;
                }
            }
        }
        return value;
    }

}
